package com.ydl.shopping.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ydl.shopping.domain.TbLoginInfo;
import com.ydl.shopping.mapper.TbLoginInfoMapper;
import com.ydl.shopping.service.ITbLoginInfoService;
import com.ydl.shopping.utils.ip.AddressUtil;
import com.ydl.shopping.utils.ip.IpUtil;
import com.ydl.shopping.utils.web.WebUtil;
import eu.bitwalker.useragentutils.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class TbLoginServiceImpl extends ServiceImpl<TbLoginInfoMapper, TbLoginInfo> implements ITbLoginInfoService {
    @Resource
    private AddressUtil addressUtils;

    @Resource
    private TbLoginInfoMapper tbLoginInfoMapper;

    @Override
    public TbLoginInfo loginRegister(String username) {
        HttpServletRequest request = WebUtil.getRequest();

        assert request != null;
        // 获取请求头中的User-Agent
        String userAgent = request.getHeader("User-Agent");
        // 获取IP地址
        String ip = IpUtil.getIpAddress(request);

        Date loginTime = new Date();
        TbLoginInfo loginInfo = new TbLoginInfo();
        // 登录用户名
        loginInfo.setUsername(username);
        // ip地址
        loginInfo.setIp(ip);
        // 登录地点
        String loginLocation = addressUtils.getIpAddress(ip);
        loginInfo.setLoginLocation(loginLocation);

        //解析agent字符串
        UserAgent agent = UserAgent.parseUserAgentString(userAgent);
        //获取浏览器对象
        Browser browser = agent.getBrowser();
        //获取操作系统对象
        OperatingSystem operatingSystem = agent.getOperatingSystem();

        // 操作系统
        String os = operatingSystem.getName();
        loginInfo.setOs(os);
        // 登录浏览器
        String browserName = browser.getName();
        loginInfo.setBrowserName(browserName);
        // 登录浏览器类型
        BrowserType browserType = browser.getBrowserType();
        loginInfo.setBrowserType(browserType.getName());
        // 登录浏览器版本
        Version browserVersion = agent.getBrowserVersion();
        if (browserVersion != null && browserVersion.getVersion() != null) {
            loginInfo.setBrowserVersion(browserVersion.getVersion());
        } else {
            loginInfo.setBrowserVersion(Browser.UNKNOWN.getName());
        }

        loginInfo.setLoginTime(loginTime);
        // 默认失败
        loginInfo.setStatus(0);

        return loginInfo;
    }

    @Override
    public void truncate() {
        tbLoginInfoMapper.truncate();
    }
}
